package com.bdqn.easybuy1.servlet.pre;

import com.bdqn.easybuy1.entities.Order;
import com.bdqn.easybuy1.entities.Product;
import com.bdqn.easybuy1.entities.User;
import com.bdqn.easybuy1.entities.UserAddress;
import com.bdqn.easybuy1.service.order.CartService;
import com.bdqn.easybuy1.service.order.CartServiceImpl;
import com.bdqn.easybuy1.service.order.OrderService;
import com.bdqn.easybuy1.service.order.OrderServiceImpl;
import com.bdqn.easybuy1.service.product.ProductCategoryService;
import com.bdqn.easybuy1.service.product.ProductCategoryServiceImpl;
import com.bdqn.easybuy1.service.product.ProductService;
import com.bdqn.easybuy1.service.product.productServiceImpl;
import com.bdqn.easybuy1.service.user.UserAddressService;
import com.bdqn.easybuy1.service.user.UserAddressServiceImpl;
import com.bdqn.easybuy1.servlet.AbstractServlet;
import com.bdqn.easybuy1.utils.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@WebServlet(name = "CartServlet", value = "/Cart")
public class CartServlet extends AbstractServlet {

    private ProductService productService;
    private CartService cartService;
    private ProductCategoryService productCategoryService;
    private UserAddressService userAddressService;
    private OrderService orderService;

    @Override
    public void init() throws ServletException {
        productService = new productServiceImpl();
        cartService = new CartServiceImpl();
        productCategoryService = new ProductCategoryServiceImpl();
        userAddressService = new UserAddressServiceImpl();
        orderService = new OrderServiceImpl();
    }

    /**
     * 添加到购物车
     *
     * @return
     */
    public ReturnResult add(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ReturnResult result = new ReturnResult();
        // 商品的id编号
        String id = request.getParameter("entityId");
        // 商品的数量字符串
        String quantityStr = request.getParameter("quantity");
        // 商品的数量
        Integer quantity = 1;
        if (!EmptyUtils.isEmpty(quantityStr)) {
            quantity = Integer.parseInt(quantityStr);
        }

        // 根据商品id查询到指定的商品对象
        Product product = productService.getProductById(Integer.valueOf(id));
        // 判断商品的库存是否足够
        if (product.getStock() < quantity) {
            return result.returnFail("商品数量不足");
        }

        //获取购物车
        ShoppingCart cart = getCartFromSession(request);
        //往购物车放置商品
        result = cart.addItem(product, quantity);

        if (result.getStatus() == Constants.ReturnResult.SUCCESS) {
            cart.setSum((EmptyUtils.isEmpty(cart.getSum()) ? 0.0 : cart.getSum()) + (product.getPrice() * quantity * 1.0));
        }
        return result;
    }

    /**
     * 从session中获取购物车
     *
     * @param request
     * @return
     */
    private ShoppingCart getCartFromSession(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        if (cart == null) {
            cart = new ShoppingCart();
            session.setAttribute("cart", cart);
        }
        return cart;
    }

    /**
     * 刷新购物车
     *
     * @param request
     * @param response
     * @return
     */
    public String refreshCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        ShoppingCart cart = getCartFromSession(request);
        cart = cartService.calculate(cart);
        session.setAttribute("cart", cart);//全部的商品
        return "/common/pre/searchBar";
    }

    /**
     * 跳到结算页面
     *
     * @param request
     * @param response
     * @return
     */
    public String toSettlement(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<ProductCategoryVo> productCategoryVoList = productCategoryService.queryAllProductCategoryList();
        //封装返回
        request.setAttribute("productCategoryVoList", productCategoryVoList);
        return "/pre/settlement/toSettlement";
    }

    /**
     * 跳转到购物车页面
     *
     * @param request
     * @param response
     * @return
     */
    public String settlement1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ShoppingCart cart = getCartFromSession(request);
        cart = cartService.calculate(cart);
        request.getSession().setAttribute("cart", cart);
        return "/pre/settlement/settlement1";
    }

    /**
     * 修改购物车信息
     *
     * @param request
     * @return
     */
    public ReturnResult modCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ReturnResult result = new ReturnResult();
        HttpSession session = request.getSession();
        String id = request.getParameter("entityId");
        String quantityStr = request.getParameter("quantity");
        ShoppingCart cart = getCartFromSession(request);
        Product product = productService.getProductById(Integer.valueOf(id));
        if (EmptyUtils.isNotEmpty(quantityStr)) {
            if (Integer.parseInt(quantityStr) > product.getStock()) {
                return result.returnFail("商品数量不足");
            }
        }
        cart = cartService.modifyShoppingCart(id, quantityStr, cart);
        session.setAttribute("cart", cart);//全部的商品
        return result.returnSuccess();
    }

    /**
     * 跳转到结算窗口
     *
     * @param request
     * @param response
     * @return
     */
    public String settlement2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = getUserFromSession(request);
        List<UserAddress> userAddressList = userAddressService.queryUserAddressList(user.getId());
        request.setAttribute("userAddressList", userAddressList);
        return "/pre/settlement/settlement2";
    }

    /**
     * 生成订单
     *
     * @param request
     * @param response
     * @return
     */
    public Object settlement3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取购物车
        ShoppingCart cart = getCartFromSession(request);
        cart = cartService.calculate(cart);

        // 获取登录的人
        User user = getUserFromSession(request);
        ReturnResult result = checkCart(request);// 重新检查购物车中的商品，看库存是否够
        if (result.getStatus() == Constants.ReturnResult.FAIL) {
            return result;
        }

        //新增地址
        String addressId = request.getParameter("addressId");
        String newAddress = request.getParameter("newAddress");
        String newRemark = request.getParameter("newRemark");
        UserAddress userAddress = new UserAddress();
        if (addressId.equals("-1")) {
            userAddress.setRemark(newRemark);
            userAddress.setAddress(newAddress);
            // 需要解决新增数据，然后返回该条数据的新增id
            userAddress.setId(userAddressService.addUserAddress(user.getId(), newAddress, newRemark));
        } else {
            userAddress = userAddressService.getUserAddressById(Integer.parseInt(addressId));
        }

        //生成订单
        Order order = orderService.payShoppingCart(cart, user, userAddress.getAddress());
        clearCart(request, response);
        request.setAttribute("currentOrder", order);
        return "/pre/settlement/settlement3";
    }

    /**
     * 清空购物车
     *
     * @param request
     * @param response
     */
    public ReturnResult clearCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ReturnResult result = new ReturnResult();
        //结账后清空购物车
        request.getSession().removeAttribute("cart");
        result.returnSuccess(null);
        return result;
    }

    private ReturnResult checkCart(HttpServletRequest request) throws Exception {
        ReturnResult result = new ReturnResult();
        ShoppingCart cart = getCartFromSession(request);
        cart = cartService.calculate(cart);
        for (ShoppingCartItem item : cart.getItems()) {
            Product product = productService.getProductById(item.getProduct().getId());
            if (product.getStock() < item.getQuantity()) {
                return result.returnFail(product.getName() + "商品数量不足");
            }
        }
        return result.returnSuccess();
    }


    /**
     * 从session中获取用户的登录信息
     *
     * @param request
     * @return
     */
    private User getUserFromSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        return user;
    }
}
